package com.santoker.gateway.config;

import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@EnableOpenApi
@Component
@Primary
public class GatewaySwaggerProvider implements SwaggerResourcesProvider {

    private static final String API_URI = "/v3/api-docs";

    private final GatewayProperties gatewayProperties;

    private static final Map<String, String> serviceMap = new HashMap<>();

    static {
        serviceMap.put("user", "用户服务");
    }


    public GatewaySwaggerProvider(GatewayProperties gatewayProperties) {
        this.gatewayProperties = gatewayProperties;
    }

    @Override
    public List<SwaggerResource> get() {
        return gatewayProperties.getRoutes()
                .stream()
                /*.filter(route -> serviceMap.containsKey(route.getId()))*/
                .map(route -> this.swaggerResource(route.getId(), route.getUri().getHost()))
                .collect(Collectors.toList());
    }

    private SwaggerResource swaggerResource(String routeId, String host) {
        String location = String.format("/%s%s", host, API_URI);
        return this.swaggerResource(serviceMap.getOrDefault(routeId, routeId), location, "lastVersion");
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

}
